// src/store/userStore.js
import { defineStore } from "pinia";
import request from "@/utils/request";

export const useUserStore = defineStore("user", {
  // state: 返回状态对象
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem("userInfo")) || null,
    token: localStorage.getItem("token") || "",
    isLoggedIn: !!localStorage.getItem("token"),
  }),

  // getters: 计算属性
  getters: {
    getName: (state) => state.userInfo?.username || "游客",
    hasToken: (state) => !!state.token,
    isAdmin: (state) => state.userInfo?.role === "ADMIN",
  },

  // actions: 同步 + 异步方法
  actions: {
    setToken(token) {
      this.token = token;
      this.isLoggedIn = true;
      localStorage.setItem("token", token);
    },
    
    removeToken() {
      this.token = "";
      this.isLoggedIn = false;
      this.userInfo = null;
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
    },
    
    setUserInfo(info) {
      this.userInfo = info;
      localStorage.setItem("userInfo", JSON.stringify(info));
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const res = await request.get("/api/user/profile");
        if (res.success) {
          this.setUserInfo(res.data);
          return res.data;
        } else {
          throw new Error(res.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.removeToken();
        throw error;
      }
    },
    
    // 退出登录
    async logout() {
      try {
        await request.post("/api/user/logout");
      } catch (error) {
        console.error("退出登录失败:", error);
      } finally {
        this.removeToken();
      }
    }
  },
});
